package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.BaseEnum.StateEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.bean.Result;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Locations;
import com.joint.base.service.DutyService;
import com.joint.base.service.UsersService;
import com.joint.base.util.BaiduMapUtil;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.Client;
import com.joint.core.entity.Linkman;
import com.joint.core.entity.ProInfo;
import com.joint.core.entity.ProInfoLog;
import com.joint.core.service.*;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by xh on 2015/3/2.
 */
@ParentPackage("com")
public class AjaxProjectAction extends BaseAdminAction {

    @Resource
    private ProInfoService proInfoService;
    @Resource
    private ClientService clientService;
    @Resource
    private LinkmanService linkmanService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private ProBackService proBackService;
    @Resource
    private ProAttendService proAttendService;
    @Resource
    private ProSignInService proSignInService;
    @Resource
    private ProinfoLogService proinfoLogService;
    @Resource
    private DutyService dutyService;
    private String dutyNum;

    protected Pager pager;

    private Users user;

    //项目类别	选数据字典
    protected ArrayList<Map<String,Object>> typesArrayList;
    private List<Client> clientList;
    private List<ProInfo> projectList;


    protected ProInfo proInfo;
   
    private String keyId;
    private String dictId;
    private String clientId;
    private String linkmanId;
    private String chiefId;
    private String locationId;
    private Set<Users> group;

    private String name;
    private String area;
    private String province;
    private String city;
    private String county;       
    private String address;
    private String groupId;
    private String start;
    private String status;
    private String modify;
    private String projectId;

    private BigDecimal longitude;
    private BigDecimal latitude;

    public void isUniqueByName() {
        PrintWriter out= null;
        try {
            out=getResponse().getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<ProInfo> proInfoList= (List<ProInfo>)proInfoService.findByPagerAndStates(null,new StateEnum[]{StateEnum.Enable}).getList();
        boolean sta = false;
        for (int i =0;i<proInfoList.size();i++){
            if (proInfoList.get(i).getName().equals(newValue) && !keyId.equals(proInfoList.get(i).getId())){
                sta = true;
                break;
            }
        }
        if (sta){
            out.print("false");
        }
        else{
            out.print("true");
        }
    }

    public String list(){

        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&&BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("state",new StateEnum[]{StateEnum.Enable});
        params.put("proState",0);
        params = getSearchFilterParams(_search,params,filters);
        if(StringUtils.isNotEmpty(clientId)) {
            Client client = clientService.get(clientId);
            if(client!=null)
                params.put("client",client);
        }

        pager=proInfoService.findByPagerAndLimit(pager,user,com,params);
        //pager = proInfoService.findByPagerAndCompanyInBuild(pager,params);

        List<ProInfo> proInfoList;
        if(pager.getTotalCount()==0){
            proInfoList= Lists.newArrayList();
        }else {
            proInfoList = (List<ProInfo>) pager.getList();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        if(proInfoList!=null && proInfoList.size()>0){
            for(ProInfo proInfo:proInfoList){
                dataRows.add(JSONObject.fromObject(proMap(proInfo)));
            }
        }
        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String listFin(){

        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("end");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&&BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }

        Users user = usersService.getLoginInfo();
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("name", name);
        params.put("state",new StateEnum[]{StateEnum.Enable});
        params.put("proState",1);
        params = getSearchFilterParams(_search,params,filters);
        //pager = proInfoService.findByPagerAndCompanyInFinish(pager,params);
        pager=proInfoService.findByPagerAndLimit(pager,user,com,params);
        List<ProInfo> proInfoList = (List<ProInfo>) pager.getList();

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        for(ProInfo proInfo:proInfoList){
            dataRows.add(JSONObject.fromObject(proMap(proInfo)));
        }
        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String listMap(){
        pager = new Pager(0);
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("start");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String, Object> rmap = Maps.newHashMap();
        rmap.put("state",StateEnum.Enable);
        if(StringUtils.isNotEmpty(clientId)) {
            Client client = clientService.get(clientId);
            if(client!=null)
                rmap.put("client",client);
        }
        if (StringUtils.isNotEmpty(projectId)){
            ProInfo project = proInfoService.get(projectId);
            if (null != project) {
                rmap.put("name",project.getName());
            }
        }

        if(StringUtils.isNotEmpty(status)) rmap.put("proState",Integer.parseInt(status));
        pager=proInfoService.findByPagerAndLimit(pager,user,com,rmap);
        //pager = proInfoService.findByPagerAndCompany(pager,null,com,rmap);
        List<ProInfo> proInfoList = (List<ProInfo>) pager.getList();

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        for(ProInfo proInfo:proInfoList){
            Map<String,Object> pMap = Maps.newHashMap();
            pMap = proMap(proInfo);
            pMap.put("time", DataUtil.DateToString(proInfo.getCreateDate()));
            dataRows.add(JSONObject.fromObject(pMap));
        }

        data.put("dataRows",dataRows);
        data.put("total",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }
    public String view(){
        dutyNum = dutyService.getDepartments(usersService.getLoginInfo(),usersService.getCompanyByUser()).size() + "";
        return "view";
    }

    public String read(){
        //LogUtil.info("keyId:" + keyId);
        if(StringUtils.isNotEmpty(keyId)){
            proInfo = proInfoService.get(keyId);
            area = "";
            if(StringUtils.isNotEmpty(proInfo.getProvince())){
                area += proInfo.getProvince();
            }
            if(StringUtils.isNotEmpty(proInfo.getCity())){
                area += proInfo.getCity();
            }
            if(StringUtils.isNotEmpty(proInfo.getCounty())){
                area += proInfo.getCounty();
            }

//            List<ProInfoLog> proInfoLogList= proinfoLogService.getByProInfo(proInfo);
//            if(proInfoLogList!=null && proInfoLogList.size()>0){
//                ProInfoLog proInfoLog=proInfoLogList.get(0);
//                if(proInfoLog!=null && proInfoLog.getChief()!=null){
//                    modify="c";
//                }
//                if(proInfoLog!= null && proInfoLog.getGroup()!=null){
//                    modify+="u";
//                }
//            }
        }
        return "read";
    }


    public String map(){
        user = usersService.getLoginInfo();
        Map<String,Object> rmap=Maps.newHashMap();
        rmap.put("state",StateEnum.Enable);
        Company company=usersService.getCompanyByUser();
        pager = clientService.findByPagerAndCompany(new Pager(0),null,usersService.getCompanyByUser(),new StateEnum[]{StateEnum.Enable});
        clientList = (List<Client>) pager.getList();
        pager = proInfoService.findByPagerAndLimit(new Pager(0),user,company,rmap);
        projectList = (List<ProInfo>) pager.getList();
        return "map";
    }

    public String isCreater(String id){
        //只有总监和新建人可编辑
        Users users=usersService.getLoginInfo();
        proInfo=proInfoService.get(id);
        if(StringUtils.equals(proInfo.getChief().getId(),users.getId()) || StringUtils.equals(proInfo.getCreater().getId(),users.getId())){
            return "block";
        }else{
            return "";
        }
    }
    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            proInfo = proInfoService.get(keyId);
        }

        Company company = usersService.getCompanyByUser();

        Map<String,Object> rMap = null;
        typesArrayList = new ArrayList<Map<String, Object>>();
        for(Dict typeObj:dictService.listFormDefinedEnable(DictBean.DictEnum.ProInfoCategory, company.getId())){
            rMap = new HashMap<String, Object>();
            rMap.put("id",typeObj.getId());
            rMap.put("name",typeObj.getName());
            rMap.put("selected","");
            if(proInfo!=null && proInfo.getCategory()!=null) {
                if( proInfo.getCategory().getId().equals(typeObj.getId())){
                    rMap.put("selected","selected");
                }
            }
            typesArrayList.add(rMap);
        }

        return  "input";
    }


    public String save(){
//        if(StringUtils.isEmpty(locationId))
//            return ajaxHtmlCallback("404", "请校验地址有效性！","操作状态");
        Users chief=null;
        if(StringUtils.isNotEmpty(keyId)){

            proInfo = proInfoService.get(keyId);
        }else{
            proInfo = new ProInfo();
            proInfo.setCreater(usersService.getLoginInfo());
        }
        proInfo.setName(name);
        if (StringUtils.isNotEmpty(dictId)){
            Dict dict = dictService.get(dictId);
            proInfo.setCategory(dict);
        }
        if (StringUtils.isNotEmpty(clientId)){
            Client client = clientService.get(clientId);
            proInfo.setClient(client);
        }
        if (StringUtils.isNotEmpty(linkmanId)){
            Linkman linkman = linkmanService.get(linkmanId);
            proInfo.setLinkman(linkman);
        }
        if (StringUtils.isNotEmpty(chiefId)){
            chief = usersService.get(chiefId);
        }
        proInfo.setProvince(province);
        proInfo.setCity(city);
        proInfo.setCounty(county);
        proInfo.setAddress(address);
        proInfo.setLocationId(locationId);
        Set<String> newSet=Sets.newHashSet();
        group = new HashSet<Users>();
        if (StringUtils.isNotEmpty(groupId)){
            String[] userIds = StringUtils.split(groupId,",");
            for (String userId : userIds){
                if(StringUtils.isEmpty(userId)) continue;
                newSet.add(userId);
                Users user = usersService.get(userId);
                group.add(user);
            }
        }
        proInfo.setStart(DataUtil.StringToDate(start, "yyyy-MM-dd"));

        proInfo.setCompany(usersService.getCompanyByUser());
        proInfo.setProState(0);
        if(StringUtils.isEmpty(keyId)){
            proInfo.setChief(chief);
            proInfo.setGroup(group);
            proInfoService.save(proInfo);
        }else{
            ProInfo oldPro = proInfoService.get(keyId);
            ProInfoLog proInfoLog = new ProInfoLog();
            Set<Users> oldList = new HashSet<Users>();
            Set<Users> newList = new HashSet<Users>();

            if (group.size() > 0) {
                for (Users us:oldPro.getGroup()) {
                    if (!group.contains(us)) {
                        Users tp = new Users();
                        tp = us;
                        oldList.add(tp);
                    }
                }
                proInfoLog.setOldgroup(oldList);
            } else {
                Set<Users> tp = new HashSet<Users>();
                for (Users us:oldPro.getGroup()) {
                    Users tmp = new Users();
                    tmp = us;
                    tp.add(tmp);
                }
                proInfoLog.setOldgroup(tp);
            }

            Set<Users> tmpSet = oldPro.getGroup();
            if (tmpSet.size() > 0) {
                for (Users us:group) {
                    if (null != tmpSet && tmpSet.size() > 0 && !tmpSet.contains(us)) {
                        Users tp = new Users();
                        tp = us;
                        newList.add(tp);
                    }
                }
                proInfoLog.setNewgroup(newList);
            } else {
                proInfoLog.setNewgroup(group);
            }

            if (oldPro.getChief().getId().equals(chief.getId())==false) {
                proInfoLog.setOldchief(oldPro.getChief());
                proInfoLog.setNewchief(chief);
            }

            proInfo.setChief(chief);
            proInfo.setGroup(group);
            proinfoLogService.updateProInfoLog(proInfo,proInfoLog);
        }
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    public String delete(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("404", "请选择项目信息！","操作状态");
        }
        ProInfo proInfo = proInfoService.get(keyId);
        //没有后续数据的才可以删除
        Pager pager = new Pager(0);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("proInfo",proInfo);
        pager = proAttendService.findByPager(pager, params);
        if (pager.getList().size()>0){
            return ajaxHtmlCallback("404", "该项目已有考勤设置信息，不能删除！","操作状态");
        }
        pager = proSignInService.findByPager(pager, params);
        if (pager.getList().size()>0){
            return ajaxHtmlCallback("404", "该项目已有签到信息，不能删除！","操作状态");
        }
        pager = proBackService.findByPager(pager, params);
        if (pager.getList().size()>0){
           return ajaxHtmlCallback("404", "该项目已有反馈信息，不能删除！","操作状态");
        }

        proInfo.setState(StateEnum.Delete);
        proInfoService.update(proInfo);
        return ajaxHtmlCallback("200", "删除成功！","操作状态");
    }

    public String finish(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("404", "请选择客户信息！","操作状态");
        }
        ProInfo proInfo = proInfoService.get(keyId);
        proInfo.setEnd(new Date());
        proInfo.setProState(1);
        proInfoService.update(proInfo);
        return ajaxHtmlCallback("200", "项目完成操作成功！","操作状态");
    }
    public String locate() throws Exception {

        proInfo = StringUtils.isEmpty(keyId)?null:proInfoService.get(keyId);

        String baiduAdd = BaiduMapUtil.localSearch(city, address);
        JSONObject jsonObj = JSONObject.fromObject(baiduAdd);
        if (jsonObj.getInt("status") == 1){
            Map addMap = Maps.newHashMap();
            addMap.put("address","");
            addMap.put("localId","");
            return ajaxHtmlAppResult(new Result(400, "地址验证失败！",addMap));
        }
        jsonObj = jsonObj.getJSONObject("result");
        jsonObj = jsonObj.getJSONObject("location");
        BigDecimal lat = BigDecimal.valueOf(jsonObj.getDouble("lat"));
        BigDecimal lng = BigDecimal.valueOf(jsonObj.getDouble("lng"));
        Result result = proInfoService.updateLocate(proInfo,lng,lat);

        return ajaxHtmlAppResult(result);
    }

    private Map<String,Object> proMap(ProInfo proInfo){
        Map<String,Object> rMap = Maps.newHashMap();
        rMap.put("id",proInfo.getId());
        rMap.put("name",proInfo.getName());
        rMap.put("chief",proInfo.getChief().getName());
        rMap.put("client",proInfo.getClient().getName());
        rMap.put("category",proInfo.getCategory().getName());
        rMap.put("linkman", proInfo.getLinkman().getName());
        rMap.put("mobile",proInfo.getLinkman().getMobile());

        String section = "";
        if (StringUtils.isNotEmpty(proInfo.getProvince())){
            section += proInfo.getProvince() + "-";
        }
        if (StringUtils.isNotEmpty(proInfo.getCity())){
            section += proInfo.getCity() + "-";
        }
        if (StringUtils.isNotEmpty(proInfo.getCounty())){
            section += proInfo.getCounty() + "-";
        }
        if (!section.equals("")){
            section = section.substring(0, section.length()-1);
        }
        rMap.put("area", section);

        rMap.put("address",proInfo.getAddress());
        if(StringUtils.isNotEmpty(proInfo.getLocationId())){
            Locations locations = locationsService.get(proInfo.getLocationId());
            if(locations!=null) {
                rMap.put("longitude", locations.getLongitude());
                rMap.put("latitude", locations.getLatitude());
            }
        }
        rMap.put("start", DataUtil.DateToString(proInfo.getStart()));
        rMap.put("end", DataUtil.DateToString(proInfo.getEnd()));
        return rMap;
    }
    @Override
    public Pager getPager() {
        return pager;
    }

    @Override
    public void setPager(Pager pager) {
        this.pager = pager;
    }

    @Override
    public String getKeyId() {
        return keyId;
    }

    @Override
    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    public String getLinkmanId() {
        return linkmanId;
    }

    public void setLinkmanId(String linkmanId) {
        this.linkmanId = linkmanId;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public ArrayList<Map<String, Object>> getTypesArrayList() {
        return typesArrayList;
    }

    public void setTypesArrayList(ArrayList<Map<String, Object>> typesArrayList) {
        this.typesArrayList = typesArrayList;
    }

    public String getDictId() {
        return dictId;
    }

    public void setDictId(String dictId) {
        this.dictId = dictId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getChiefId() {
        return chiefId;
    }

    public void setChiefId(String chiefId) {
        this.chiefId = chiefId;
    }

    public Set<Users> getGroup() {
        return group;
    }

    public void setGroup(Set<Users> group) {
        this.group = group;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getStart() {
        return start;
    }

    public void setStart(String start) {
        this.start = start;
    }

    public ProInfo getProInfo() {
        return proInfo;
    }

    public void setProInfo(ProInfo proInfo) {
        this.proInfo = proInfo;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public BigDecimal getLongitude() {
        return longitude;
    }

    public void setLongitude(BigDecimal longitude) {
        this.longitude = longitude;
    }

    public BigDecimal getLatitude() {
        return latitude;
    }

    public void setLatitude(BigDecimal latitude) {
        this.latitude = latitude;
    }

    public List<Client> getClientList() {
        return clientList;
    }

    public void setClientList(List<Client> clientList) {
        this.clientList = clientList;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }

    public String getLocationId() {
        return locationId;
    }

    public void setLocationId(String locationId) {
        this.locationId = locationId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getModify() {
        return modify;
    }

    public void setModify(String modify) {
        this.modify = modify;
    }

    public String getDutyNum() {
        return dutyNum;
    }

    public void setDutyNum(String dutyNum) {
        this.dutyNum = dutyNum;
    }

    public List<ProInfo> getProjectList() {
        return projectList;
    }

    public void setProjectList(List<ProInfo> projectList) {
        this.projectList = projectList;
    }

    public String getProjectId() {
        return projectId;
    }

    public void setProjectId(String projectId) {
        this.projectId = projectId;
    }
}
